package com.pisolution.actuator.service.model;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author likai
 * @version 1.0.0
 * @ClassName PageActionResult.java
 * @Description TODO
 * @createTime 2021年09月14日 11:13:00
 */
@Data
public class PageActionResult<T> {
    private Long totalRecords;
    private Integer totalPages;
    private Integer pageNumber;
    private Integer pageSize;
    private List<T> datas = new ArrayList();
    public PageActionResult() {
    }

    public PageActionResult(Long totalRecords, Integer totalPages, Integer pageNumber, Integer pageSize, List<T> datas) {
        this.totalRecords = totalRecords;
        this.totalPages = totalPages;
        this.pageNumber = pageNumber;
        this.pageSize = pageSize;
        this.datas = datas;
    }

    public PageActionResult(IPage<T> page) {
        this.totalRecords = page.getTotal();
        this.totalPages = Math.toIntExact(page.getPages());
        this.pageNumber = Math.toIntExact(page.getCurrent());
        this.pageSize = Math.toIntExact(page.getSize());
        this.datas = page.getRecords();
    }

    public PageActionResult(List<T> list, int pageNumber, int pageSize) {
        if (pageSize == 0) {
            this.totalRecords = (long)list.size();
            this.totalPages = this.totalRecords > 0L ? 1 : 0;
            this.pageNumber = this.totalRecords > 0L ? 1 : 0;
            this.pageSize = list.size();
            this.datas = list;
        } else {
            this.totalRecords = (long)list.size();
            this.pageSize = pageSize > 0 ? pageSize : Integer.parseInt("10");
            this.totalPages = (int)(this.totalRecords / (long)this.pageSize + (long)(this.totalRecords % (long)this.pageSize == 0L ? 0 : 1));
            if (pageNumber < 1) {
                this.pageNumber = 1;
            } else if (pageNumber > this.totalPages) {
                this.pageNumber = this.totalPages;
            } else {
                this.pageNumber = pageNumber;
            }
            if (CollectionUtils.isEmpty(list)) {
                this.datas = list;
            } else {
                int from = (this.pageNumber - 1) * this.pageSize;
                int to = this.pageNumber * this.pageSize;
                if (from < 0) {
                    from = 0;
                }
                if (to < 0) {
                    to = 0;
                }
                if (from >= list.size()) {
                    from = list.size() - 1;
                }
                if (to > list.size()) {
                    to = list.size();
                }
                this.datas = list.subList(from, to);
            }
        }
    }
}
